package com.wangjw.coreTechnology;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by wangjw on 18/7/19.
 */
public class RWSample {

    private final Map<String, String> map = new TreeMap<>();
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock readLock = readWriteLock.readLock();
    private final Lock writeLock = readWriteLock.writeLock();

    public String get(String key) {
        readLock.lock();
        System.out.println("读锁锁定！");
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public String put(String key, String value) {
        writeLock.lock();
        System.out.println("写锁锁定！");
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }
}
